import {
  ESpecimenStatus,
  ESpeimenTableColumnKey,
  getSpecimentMergeKey,
  specimenColumns,
} from "@scmt/api-common";
import { SpecimenEntity } from "@scmt/api-lis-specimen";
import { TableProps } from "@scmt/common-components";

type Data = globalThis.Ref<{
  items: SpecimenEntity[];
  pagination: {
    pageNum: number;
    pageSize: number;
    total: number;
  };
}>;

export const useGroup = (data: Data) => {
  const groupIndex = computed(() => {
    const { items } = data.value;

    const groupMap = items.reduce((acc, cur, index) => {
      const mergeKey = getSpecimentMergeKey(cur);
      const key = cur[mergeKey];
      if (key && !Object.prototype.hasOwnProperty.call(acc, key)) {
        acc[key] = [
          index,
          items.findLastIndex((item) => item[mergeKey] === key),
        ];
      }

      return acc;
    }, {} as Record<string, [number, number]>);

    return Object.values(groupMap).filter(([start, end]) => start !== end);
  });

  const getCellClassName: TableProps["cellClassName"] = ({
    column,
    rowIndex,
  }) => {
    if (
      column.property ===
      specimenColumns[ESpeimenTableColumnKey.ApplicationProject].prop
    ) {
      if (groupIndex.value.length) {
        const [start, end] =
          groupIndex.value.find(
            ([start, end]) =>
              (start < rowIndex && rowIndex < end) ||
              start === rowIndex ||
              end === rowIndex
          ) || [];

        if (start !== void 0 && end !== void 0) {
          const middle = start + Math.ceil((end - start) / 2);
          const remain = (end - start) % 2;

          switch (rowIndex) {
            case start:
              return "group--start";
            case end:
              return `group--end ${
                middle === end
                  ? `group-text ${remain ? "group-text--offset" : ""}`
                  : ""
              } `;
            case middle:
              return "group--content group-text";
            default:
              return "group--content";
          }
        }
      }
    }

    return "";
  };

  const spanMethod: TableProps["spanMethod"] = ({ column, rowIndex }) => {
    if (["_selection", "_operation"].includes(column.property)) {
      const [start, end] =
        groupIndex.value.find(
          ([start, end]) =>
            (start < rowIndex && rowIndex < end) ||
            start === rowIndex ||
            end === rowIndex
        ) || [];

      if (start !== void 0 && end !== void 0) {
        if (rowIndex === start) {
          return [end - start + 1, 1];
        } else {
          return [0];
        }
      }
    }
  };

  /**
   * 获取合并的key
   * @param specimen
   * @returns
   */
  const getGroupKey = (specimen: SpecimenEntity) => {
    const { state } = specimen;
    switch (true) {
      case state !== ESpecimenStatus.NOTGENERATED:
        return "barcode";
      default:
        return "checkId";
    }
  };

  return {
    getCellClassName,
    spanMethod,
    getGroupKey,
  };
};
